#ifndef _GATEWAY_STREAM_H_
#define _GATEWAY_STREAM_H_

#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>

class gateway_stream_event;
class gateway_stream : public boost::enable_shared_from_this<gateway_stream>
{
public:
	gateway_stream(boost::asio::io_service& ioservice);
	~gateway_stream();

	void open();
	void close();
	bool is_open();
	void set_timeout(unsigned int timeout);
	void set_event_handle(gateway_stream_event* stream_event);
	boost::asio::ip::tcp::socket& get_socket();
	int send(unsigned char* data, unsigned int len);
	std::string get_remote_host();
	unsigned short get_remote_port();
private:
	void do_error(bool inner);
	void handle_timer(const boost::system::error_code& error);
	void handle_read(const boost::system::error_code& error, size_t transferred);
	void handle_idle_connection(const boost::system::error_code& error);
	void assign_copy();
private:
	unsigned int _cache;
	unsigned int _total;
	unsigned int _timeout;
	unsigned char* _buffer;
	volatile boost::uint32_t _error_state;
	boost::asio::strand _io_strand;
	boost::asio::deadline_timer _timer;
	gateway_stream_event* _stream_event;
	boost::asio::ip::tcp::socket _socket;
	boost::posix_time::ptime _last_readwrite_time;
};

typedef boost::shared_ptr<gateway_stream>gateway_stream_ptr;

#endif
